package com.guaoran.activity.aop;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.guaoran.common.datasource.DataSourceTypeManager;
import com.guaoran.common.datasource.DataSources;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author : guaoran
 * @Description  动态切换数据源
 * @date :2019/4/15 21:41
 */
@Aspect
@Component
@Order(0)
public class DataSourceInterceptor {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Pointcut("(" +
            "execution(public * com.guaoran.activity.services.*.get*(..)) " +
            ")")
    public void dataSourceSlave(){};

    /**
     *  切换数据源
     * @param joinPoint
     */
    @Before("dataSourceSlave()")
    public void before(JoinPoint joinPoint) {
        DataSources slave = DataSources.SLAVE;
        if(System.currentTimeMillis()%2==0){
            slave = DataSources.SLAVE1;
        }
        DataSourceTypeManager.set(slave);
        logger.debug("activity...before...set:"+DataSourceTypeManager.get());

    }

    /**
     * 还原数据源
     * @param joinPoint
     */
    @After("dataSourceSlave()")
    public void after (JoinPoint joinPoint){
        DataSourceTypeManager.reset();
        logger.debug("activity...after...reset:"+DataSourceTypeManager.get());
    }
}
